import { View } from '@tarojs/components'
import F2Canvas from 'taro-f2-react'
import { Chart, Interval, Axis, Legend } from '@antv/f2'

interface IBarChartsProps {
  id?: string
  data?: any[]
  fieldNames?: {
    [key: string]: string
  }
  fontSize?: number
}

function getTickValue (arr: any[]) {
  const results = arr.map(({ value }) => value)
  let max = results[0]
  results.forEach(item => (max = item > max ? item : max))
  return Math.ceil(max / 5)
}

const IBarGroupChartsIndex: React.FC<IBarChartsProps> = props => {
  const {
    id,
    data = [],
    fieldNames = { label: 'name', value: 'totalNum' },
    fontSize = 14
  } = props

  const sourceData = data || []

  return (
    <View style={{ width: '100%', height: '260px' }} className='chart_body'>
      {sourceData.length > 0 ? (
        <F2Canvas id={id}>
          <Chart
            data={sourceData}
            scale={{
              [fieldNames.value]: {
                type: 'linear',
                tickInterval: getTickValue(sourceData)
              }
            }}
          >
            <Axis field={fieldNames.label} style={{ label: { fontSize } }} />
            <Axis field={fieldNames.value} />
            <Interval
              x={fieldNames.label}
              y={fieldNames.value}
              color={['name', ['#3e73fe', '#f7ba1e']]}
              adjust='stack'
            />
            <Legend
              position='bottom'
              style={{
                flexDirection: 'row',
                justifyContent: 'center'
              }}
              clickable={false}
            />
          </Chart>
        </F2Canvas>
      ) : null}
    </View>
  )
}

export default IBarGroupChartsIndex
